package org.moonlight.jvm.rtda.share.heap.classmember;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.moonlight.jvm.classfile.MemberInfo;
import org.moonlight.jvm.classfile.attribute.ConstantValueAttribute;
import org.moonlight.jvm.rtda.share.heap.Class;

/**
 * 字段信息类 - 存储 Class 中的字段信息
 *
 * @author Moonlight
 * @createTime 2023/8/29 16:33
 **/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class Field extends ClassMember {

    private int constValueIndex;
    private int slotId;

    public void copyAttributes(MemberInfo info) {
        ConstantValueAttribute attribute = info.constantValueAttribute();
        if (attribute != null) {
            this.constValueIndex = attribute.getConstantValIdx();
        }
    }

    /**
     * 根据 解析出来的 {@link Class} 和 {@link MemberInfo}
     * 构建 {@link Field}
     *
     * @param clazz {@link Class}
     * @param classFileFields {@link MemberInfo}
     * @return Field[]
     * @createTime 16:37 2023/8/29
     * @author moonlight
     **/
    public static Field[] newFields(Class clazz, MemberInfo[] classFileFields) {
        Field[] fields = new Field[classFileFields.length];
        for (int i = 0; i < classFileFields.length; i++) {
            fields[i] = new Field();
            fields[i].clazz = clazz;
            fields[i].copyMemberInfo(classFileFields[i]);
            fields[i].copyAttributes(classFileFields[i]);
        }
        return fields;
    }

    public boolean isLongOrDouble() {
        return "J".equals(this.descriptor) || "D".equals(this.descriptor);
    }
}
